import axios from 'axios'
import store from '@/store/index.js'

let baseUrl = ''
if (process.env.NODE_ENV === "development") { // 开发环境
  baseUrl = process.env.VUE_APP_BASEURL
} else if (process.env.NODE_ENV === "production") { //生产环境
  baseUrl = process.env.VUE_APP_BASEURL
} else if (process.env.NODE_ENV === "test") { //测试环境
  baseUrl = process.env.VUE_APP_BASEURL
}

const instance = axios.create({
  baseURL: baseUrl,
  timeout: 50000,
})
const upload = axios.create({
  baseURL: baseUrl,
  // timeout: 50000,
  headers: { "Content-Type": "multipart/form-data" }
})

upload.interceptors.request.use(
  function (config) {
    let token = store.state.userInfo.token
    token = window.localStorage.getItem('token')
    config.headers.language = 'zh-cn'
    if (token) {
      //将token放到请求头发送给服务器,将tokenkey放在请求头中
      config.headers.token = token;
      return config;
    }
    return config
  },
  function (error) {
    return error
  })
upload.interceptors.response.use(
  function (response) {
    return response
  },
  function (error) {
    return error
  })

instance.interceptors.request.use(
  function (config) {
    let token = store.state.userInfo.token
    token = window.localStorage.getItem('token')
    config.headers.language = 'zh-cn'
    if (token) {
      //将token放到请求头发送给服务器,将tokenkey放在请求头中
      config.headers.token = token;
      return config;
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  })

instance.interceptors.response.use(
  function (response) {
    return response
  },
  function (error) {
    {
      switch (error && error.response && error.response.status) {
        case 400:
          error.message = '请求错误'
          break
        case 401:
          error.message = '未授权，请登录'
          break
        case 403:
          error.message = '拒绝访问'
          break
        case 404:
          error.message = '未找到访问地址'
          break
        case 408:
          error.message = '请求超时'
          break
        case 500:
          error.message = '服务器内部错误'
          break
        case 501:
          error.message = '服务未实现'
          break
        case 502:
          error.message = '网关错误'
          break
        case 503:
          error.message = '服务不可用'
          break
        case 504:
          error.message = '网关超时'
          break
        case 505:
          error.message = 'HTTP版本不受支持'
          break
        default:
      }
      //Do something with response error
      return error;
    }
  })

export function get(url, params) {
  return instance.get(url, { params })
}

export function post(url, data) {

  return instance.post(url, data)
}


export function post2(url, data) {

  return upload.post(url, data)
}

